<template>
  <div>
    <!-- 利润表提报 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">

      <FilterTable
        ref="table"
        columnsRef="qjhIncomeReportSubmit"
        :height="'auto'"
        :isToperInfo="false"
        :isColumnFilter="false"
        :isSelectColumn="false"
        :columns="columns"
        :dataSource="tableList"
        :onSyncTableData="tableChangeFun"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls">
           <el-button size="small" type="text" style="font-size:14px; font-weight:bold;margin-right:20px;color:red;width: calc(100vw - 420px);text-align: left;">
             <span v-text="`当前状态：${this.currStatus}`"></span>
           </el-button>

          <el-button size="small" type="primary" @click="importHandle">导 入</el-button>
          <multiuse-button size="small" type="primary" :disabled="!reportId" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
      <div style="height:30px;"></div>
      <FormPanel ref="formPanel" :list="formList" @formChange="formChangeHandle" :isSubmitBtn="false" :collapse="false" />
      <div
        :style="{
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <multiuse-button size="small" type="primary" v-show="isShow" :click="dataHandle.bind(this, 60771002)">提 交</multiuse-button>
        <multiuse-button size="small" type="primary" v-show="isShow" :click="dataHandle.bind(this, 60771001)">保 存</multiuse-button>
      </div>
    </Spin>

    <BaseDialog :visible.sync="isImport" title="数据导入" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ImportFile :importData="formData" @close="emitCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import moment from 'moment';
import { getOwnerCode } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import { queryList, exportExcel, saveOne,exporturl } from '@/api/dealerFinance/CRReportManage/IncomeReportSubmit';
import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire'; //获取登录信息
import ImportFile from '../ImportFile';

export default {
  name: 'IncomeReportSubmit',
  mixins: [dictionary],
  components: {
    ImportFile
  },
  data() {
    this.BaseTable = null;
    this.saveData = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      formList: this.createdFrom1(),
      dealerName: '',
      exportLoading: false,
      isImport: false,
      isShow: true,
      formData: {},
      tableList: [],
      reportId: '',
      year: moment().format('YYYY'),
      month: moment().format('MM'),
      currStatus:''
    };
  },
  created() {
    this.getDealerName();
    this.getList(moment().format('YYYY'), moment().format('MM'));
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },

  methods: {
    // 获取登录信息
    async getDealerName() {
      const res = await getLoginUser();
      if (res.resultCode == 200) {
        this.dealerName = res.data.dealerName;
      }
    },
    tableChangeFun(val) {
      if (val && val.length > 0) {
        // 设置不可编辑-行列
        let arr = [];
        for (let i = 0; i < val.length; i++) {
          arr.push(val[i]);
        }
        this.BaseTable.SET_CELL_UNEDITABLE(arr, 'column1', true);
        this.BaseTable.SET_CELL_UNEDITABLE(arr, 'column2', true);
        this.BaseTable.SET_CELL_UNEDITABLE([val[0], val[1], val[5], val[10], val[15], val[17]], 'column3', true);
        this.BaseTable.SET_CELL_UNEDITABLE([val[0], val[1], val[5], val[10], val[15], val[17]], 'column4', true);

        // 计算主营业务 10=1-2-5
        val[5].column3 = (val[2].column3 * 10000 - val[3].column3 * 10000 - val[4].column3 * 10000) / 10000;
        val[5].column4 = (val[2].column4 * 10000 - val[3].column4 * 10000 - val[4].column4 * 10000) / 10000;
        // 营业利润 18=10+11-13-14-15
        val[10].column3 = (val[5].column3 * 10000 + val[6].column3 * 10000 - val[7].column3 * 10000 - val[8].column3 * 10000 - val[9].column3 * 10000) / 10000;
        val[10].column4 = (val[5].column4 * 10000 + val[6].column4 * 10000 - val[7].column4 * 10000 - val[8].column4 * 10000 - val[9].column4 * 10000) / 10000;

        // 利润总额 27=18+19+22+23-25
        val[15].column3 = (val[10].column3 * 10000 + val[11].column3 * 10000 + val[12].column3 * 10000 + val[13].column3 * 10000 - val[14].column3 * 10000) / 10000;
        val[15].column4 = (val[10].column4 * 10000 + val[11].column4 * 10000 + val[12].column4 * 10000 + val[13].column4 * 10000 - val[14].column4 * 10000) / 10000;
        // 净利率 30=27-28
        val[17].column3 = (val[15].column3 * 10000 - val[16].column3 * 10000) / 10000;
        val[17].column4 = (val[15].column4 * 10000 - val[16].column4 * 10000) / 10000;

        // 保存提交的数据
        this.saveData = {
          reportYear: this.year, // 提报年度
          reportMonth: this.month, // 提报月度

          byzyywsr: val[2].column3, // 主营业务收入（本月）

          byzyywcb: val[3].column3, // 主营业务成本（本月）

          byzyywsjjfj: val[4].column3, // 主营业务税金及附加（本月）

          byzyywlr: val[5].column3, // 主营业务利润（本月）

          byqtywlr: val[6].column3, //其他业务利润（本月）

          byyyfy: val[7].column3, // 营业费用（本月）

          byglfy: val[8].column3, // 管理费用（本月）

          bycwfy: val[9].column3, // 财务费用（本月）

          byyylr: val[10].column3, // 营业利润（本月）

          bytzsy: val[11].column3, // 投资收益（本月）

          bybtsr: val[12].column3, // 补贴收入（本月）

          byyywsr: val[13].column3, // 营业外收入（本月）

          byyywzc: val[14].column3, // 营业外支出（本月）

          bylrze: val[15].column3, // 利润总额（本月）

          bysds: val[16].column3, // 所得税（本月）

          byjlr: val[17].column3, // 净利润（本月）

          bnzyywsr: val[2].column4, // 主营业务收入（本年）

          bnzyywcb: val[3].column4, // 主营业务成本（本年）

          bnzyywsjjfj: val[4].column4, // 主营业务税金及附加（本年）

          bnzyywlr: val[5].column4, // 主营业务利润（本年）

          bnqtywlr: val[6].column4, // 其他业务利润（本年）

          bnyyfy: val[7].column4, // 营业费用（本年）

          bnglfy: val[8].column4, // 管理费用（本年）

          bncwfy: val[9].column4, // 财务费用（本年）

          bnyylr: val[10].column4, // 营业利润（本年）

          bntzsy: val[11].column4, // 投资收益（本年）

          bnbtsr: val[12].column4, // 补贴收入（本年）

          bnyywsr: val[13].column4, // 营业外收入（本年）

          bnyywzc: val[14].column4, // 营业外支出（本年）

          bnlrze: val[15].column4, // 利润总额（本年）

          bnsds: val[16].column4, // 所得税（本年）

          bnjlr: val[17].column4 // 净利润（本年）
        };
      }
      console.log(val, this.saveData, '---奥利给---');
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    changeHandle(params) {
      this.year = params.yearMonth.split('-')[0];
      this.month = params.yearMonth.split('-')[1];

      this.getList(this.year, this.month);
      this.columns[3].title = `月度：${this.year}年${this.month}月`;
    },
    resetChange(params) {
      this.year = params.yearMonth.split('-')[0];
      this.month = params.yearMonth.split('-')[1];

      this.getList(this.year, this.month);
      this.columns[3].title = `月度：${this.year}年${this.month}月`;
    },
    // 导入
    importHandle() {
      this.isImport = true;
      this.formData.name = '利润表导入';
      this.formData.upUrl = 'https://bjev-cms-oss-public.oss-cn-beijing.aliyuncs.com/利润表导入.xlsx';
      this.formData.importUrl = '/api/cmscloud.wholesales/profit/upload';
    },
    emitCloseHandler(val, type) {
      this.isImport = val;
      if (type === 'refresh') {
        // 重新加载
        this.getList(this.year, this.month);
      }
    },
    // 表单数据
    formChangeHandle(val) {
      this.saveData = Object.assign({}, this.saveData, val);
    },
    // 保存提交
    async dataHandle(status) {
      if (this.BaseTable.GET_REQUIRED_ERROR() != null) return;

      this.saveData.id = this.reportId ? this.reportId : ''; // Id
      this.saveData.profitStatus = status; // 状态
      this.saveData.checkDesc = this.formList[0].initialValue;

      const res = await saveOne(this.saveData);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '操作成功' });
        this.getList(this.year, this.month);
      }
    },
    // 查询列表
    async getList(Year = '', Month = '') {
      this.exportLoading = true;
      const res = await queryList({ reportYear: Year, reportMonth: Month });
      this.reportId = '';
      this.tableList = [];
      this.formList[0].initialValue = '';

      if (res.resultCode == 200) {
        if (res.data) {
          const data = res.data; // 表格
          this.reportId = data.id; // 导出传id

          this.currStatus = this.createDictText(data.profitStatus, '6077');

          this.tableList = [
            {
              column1: '编制单位:',
              column2: data.dealerCode,
              column3: data.dealerName,
              column4: '单位：元'
            },
            {
              column1: '项    目',
              column2: '行次',
              column3: '本月数',
              column4: '本年累计数'
            },
            {
              column1: '一、主营业务收入',
              column2: '1',
              column3: data.byzyywsr,
              column4: data.bnzyywsr
            },
            {
              column1: '减：主营业务成本',
              column2: '2',
              column3: data.byzyywcb,
              column4: data.bnzyywcb
            },
            {
              column1: '主营业务税金及附加',
              column2: '5',
              column3: data.byzyywsjjfj,
              column4: data.bnzyywsjjfj
            },
            {
              column1: '二、主营业务利润（亏损以“－”号填列）',
              column2: '10=1-2-5',
              column3: data.byzyywlr,
              column4: data.bnzyywlr
            },
            {
              column1: '加：其他业务利润（亏损以“－”号填列）',
              column2: '11',
              column3: data.byqtywlr,
              column4: data.bnqtywlr
            },
            {
              column1: '减： 营业费用',
              column2: '13',
              column3: data.byyyfy,
              column4: data.bnyyfy
            },
            {
              column1: '管理费用',
              column2: '14',
              column3: data.byglfy,
              column4: data.bnglfy
            },
            {
              column1: '财务费用',
              column2: '15',
              column3: data.bycwfy,
              column4: data.bncwfy
            },
            {
              column1: '三、营业利润（亏损以“－”号填列）',
              column2: '18=10+11-13-14-15',
              column3: data.byyylr,
              column4: data.bnyylr
            },
            {
              column1: '加：投资收益（损失以“－”号填列）',
              column2: '19',
              column3: data.bytzsy,
              column4: data.bntzsy
            },
            {
              column1: '补贴收入',
              column2: '22',
              column3: data.bybtsr,
              column4: data.bnbtsr
            },
            {
              column1: '营业外收入',
              column2: '23',
              column3: data.byyywsr,
              column4: data.bnyywsr
            },
            {
              column1: '减：营业外支出',
              column2: '25',
              column3: data.byyywzc,
              column4: data.bnyywzc
            },
            {
              column1: '四、利润总额（亏损总额以“－”号填列）',
              column2: '27=18+19+22+23-25',
              column3: data.bylrze,
              column4: data.bnlrze
            },
            {
              column1: '减：所得税',
              column2: '28',
              column3: data.bysds,
              column4: data.bnsds
            },
            {
              column1: '五、净利润（净亏损以“－”号填列）',
              column2: '30=27-28',
              column3: data.byjlr,
              column4: data.bnjlr
            }
          ];
          // 驳回意见赋值
          this.formList[0].initialValue = data.checkDesc;
          if (60771002 == data.profitStatus) {
            this.isShow = false; // 已提交数据不展示按钮
            this.columns.map(x => {
              x.editable = false;
            });
          } else {
            this.isShow = true; // 未提交数据展示按钮
            this.columns.map(x => {
              x.editable = true;
            });
          }
        } else {
           this.currStatus = '';
          this.isShow = true; // 未提交数据展示按钮
          this.columns.map(x => {
            x.editable = true;
          });
          this.tableList = [
            {
              column1: '编制单位:',
              column2: getOwnerCode(),
              column3: this.dealerName,
              column4: '单位：元'
            },
            {
              column1: '项    目',
              column2: '行次',
              column3: '本月数',
              column4: '本年累计数'
            },
            {
              column1: '一、主营业务收入',
              column2: '1',
              column3: 0,
              column4: 0
            },
            {
              column1: '减：主营业务成本',
              column2: '2',
              column3: 0,
              column4: 0
            },
            {
              column1: '主营业务税金及附加',
              column2: '5',
              column3: 0,
              column4: 0
            },
            {
              column1: '二、主营业务利润（亏损以“－”号填列）',
              column2: '10=1-2-5',
              column3: 0,
              column4: 0
            },
            {
              column1: '加：其他业务利润（亏损以“－”号填列）',
              column2: '11',
              column3: 0,
              column4: 0
            },
            {
              column1: '减： 营业费用',
              column2: '13',
              column3: 0,
              column4: 0
            },
            {
              column1: '管理费用',
              column2: '14',
              column3: 0,
              column4: 0
            },
            {
              column1: '财务费用',
              column2: '15',
              column3: 0,
              column4: 0
            },
            {
              column1: '三、营业利润（亏损以“－”号填列）',
              column2: '18=10+11-13-14-15',
              column3: 0,
              column4: 0
            },
            {
              column1: '加：投资收益（损失以“－”号填列）',
              column2: '19',
              column3: 0,
              column4: 0
            },
            {
              column1: '补贴收入',
              column2: '22',
              column3: 0,
              column4: 0
            },
            {
              column1: '营业外收入',
              column2: '23',
              column3: 0,
              column4: 0
            },
            {
              column1: '减：营业外支出',
              column2: '25',
              column3: 0,
              column4: 0
            },
            {
              column1: '四、利润总额（亏损总额以“－”号填列）',
              column2: '27=18+19+22+23-25',
              column3: 0,
              column4: 0
            },
            {
              column1: '减：所得税',
              column2: '28',
              column3: 0,
              column4: 0
            },
            {
              column1: '五、净利润（净亏损以“－”号填列）',
              column2: '30=27-28',
              column3: 0,
              column4: 0
            }
          ];
        }
      }else{
         this.currStatus = '';
      }
      this.exportLoading = false;
    },
    // 导出
    async exportHandle() {
        let json = Object.assign({}, { CODE: 'CODE_0000022' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;
      //     let param = { id: this.reportId };
      //     exportExcel(param)
      //       .then(response => {
      //         exportExcelFile(response.data, '利润表提报');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },

    createdFrom() {
      return [
        {
          type: 'DATE',
          label: '月度',
          fieldName: 'yearMonth',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM'),
          placeholder: '请选择'
        }
      ];
    },
    createdFrom1() {
      return [
        {
          type: 'TEXT_AREA',
          label: '驳回意见',
          fieldName: 'checkDesc',
          initialValue: '',
          selfCols: 3,
          placeholder: '',
          disabled: true
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '利润表',
          dataIndex: 'column1',
          filterType: 'input',
          align: 'center'
        },
        {
          title: '',
          dataIndex: 'column2',
          filterType: 'input',
          align: 'center'
        },
        {
          title: '',
          dataIndex: 'column3',
          filterType: 'input',
          align: 'center',
          showOverflowTooltip: false,
          editType: 'number',
          defaultEditable: true,
          editable: true,
          editRequired: true,
          msgtitle: '当前项',
          max: 999999999,
          min: -999999999
        },
        {
          title: `月度：${moment().format('YYYY')}年${moment().format('MM')}月`,
          dataIndex: 'column4',
          filterType: 'input',
          align: 'center',
          showOverflowTooltip: false,
          editType: 'number',
          defaultEditable: true,
          editable: true,
          editRequired: true,
          msgtitle: '当前项',
          max: 999999999,
          min: -999999999
        }
      ];
    }
  }
};
</script>
